/*
 * Copyright 2002-2023 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.web.servlet.handler;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.springframework.beans.BeansException;
import org.springframework.util.CollectionUtils;

/**
 * <p>
 *     RequestMappingHandlerMapping 和通过 ViewControllerRegistry.buildHandlerMapping() 方法生成的 AbstractHandlerMapping 实例（通常为 SimpleUrlHandlerMapping），
 *     都是 Spring MVC 中用于将传入的 HTTP 请求映射到处理器的不同实现。尽管它们都实现了 HandlerMapping 接口，
 *     但它们的工作方式和使用场景有着显著的区别。
 *
 *     1、RequestMappingHandlerMapping
 * 		功能概述
 * 			基于注解的映射：RequestMappingHandlerMapping 是一个专门用于处理带有 @RequestMapping 注解的方法的处理器映射器。
 * 			灵活性和强大功能：支持多种条件来匹配请求，包括 URL 模式、HTTP 方法、请求参数、头部信息等。
 * 			自动注册：在大多数情况下，Spring Boot 会自动注册此映射器并扫描所有带有 @RequestMapping 注解的方法。
 * 		使用场景
 * 			RESTful Web 服务：非常适合构建 RESTful API，能够根据请求的详细信息精确地路由到相应的控制器方法。
 * 			复杂路由需求：当需要基于多个条件（如请求方法、参数、头部等）进行复杂的路由时非常有用。
 *
 * 		示例代码
 * 			import org.springframework.web.bind.annotation.RequestMapping;
 * 			import org.springframework.web.bind.annotation.RestController;
 * 			@RestController
 * 			public class MyController {
 *     			@RequestMapping("/hello")
 *    		 	public String hello() {
 *        			 return "Hello, World!";
 *     			}
 * 			}
 * 			在这个例子中，RequestMappingHandlerMapping 会自动发现并注册 MyController 类中的 hello() 方法作为处理器来处理 /hello 路径的请求。
 *
 *	2、ViewControllerRegistry.buildHandlerMapping()
 * 		功能概述
 *			 简化视图映射：ViewControllerRegistry 是 Spring 提供的一个工具类，允许开发者快速注册简单的视图控制器，这些控制器主要用于直接返回视图而不需要经过复杂的控制器逻辑。
 * 			 生成 SimpleUrlHandlerMapping：调用 buildHandlerMapping() 方法后，会生成一个 SimpleUrlHandlerMapping 实例，它负责将特定的 URL 映射到指定的视图名称。
 * 			 轻量级：适合于那些只需要简单页面重定向或直接返回视图的应用场景。
 * 		使用场景
 * 			静态页面展示：当你有静态页面需要展示，并且不需要任何业务逻辑处理时，可以使用 ViewControllerRegistry 快速配置这些映射。
 * 			简化配置：对于一些简单的前端跳转需求，避免编写额外的控制器类，使得配置更加简洁。
 * 		示例代码
 * 			import org.springframework.context.annotation.Configuration;
 * 			import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
 * 			import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
 * 			@Configuration
 * 			public class MvcConfig implements WebMvcConfigurer {
 *     			@Override
 *     			public void addViewControllers(ViewControllerRegistry registry) {
 *         			registry.addViewController("/home").setViewName("home");
 *         			registry.addViewController("/").setViewName("home");
 *         			registry.addViewController("/hello").setViewName("hello");
 *     			}
 * 			}
 * 			在此配置中，我们向 ViewControllerRegistry 注册了几个 URL 到视图名称的映射。例如，当用户访问 /home 或根路径 / 时，将直接渲染名为 home 的视图。
 *
 *
 * </p>
 * Implementation of the {@link org.springframework.web.servlet.HandlerMapping}
 * interface that maps from URLs to request handler beans. Supports both mapping to bean
 * instances and mapping to bean names; the latter is required for non-singleton handlers.
 *
 * <p>The "urlMap" property is suitable for populating the handler map with
 * bean references, e.g. via the map element in XML bean definitions.
 *
 * <p>Mappings to bean names can be set via the "mappings" property, in a form
 * accepted by the {@code java.util.Properties} class, as follows:
 *
 * <pre class="code">
 * /welcome.html=ticketController
 * /show.html=ticketController</pre>
 *
 * <p>The syntax is {@code PATH=HANDLER_BEAN_NAME}. If the path doesn't begin
 * with a slash, one is prepended.
 *
 * <p>Supports direct matches (given "/test" -&gt; registered "/test") and "*"
 * matches (given "/test" -&gt; registered "/t*"). For details on the pattern
 * options, see the {@link org.springframework.web.util.pattern.PathPattern}
 * javadoc.

 * @author Rod Johnson
 * @author Juergen Hoeller
 * @author Sam Brannen
 * @see #setMappings
 * @see #setUrlMap
 * @see BeanNameUrlHandlerMapping
 */
public class SimpleUrlHandlerMapping extends AbstractUrlHandlerMapping {

	private final Map<String, Object> urlMap = new LinkedHashMap<>();


	/**
	 * Create a {@code SimpleUrlHandlerMapping} with default settings.
	 */
	public SimpleUrlHandlerMapping() {
	}

	/**
	 * Create a {@code SimpleUrlHandlerMapping} using the supplied URL map.
	 * @param urlMap map with URL paths as keys and handler beans (or handler
	 * bean names) as values
	 * @since 5.2
	 * @see #setUrlMap(Map)
	 */
	public SimpleUrlHandlerMapping(Map<String, ?> urlMap) {
		setUrlMap(urlMap);
	}

	/**
	 * Create a {@code SimpleUrlHandlerMapping} using the supplied URL map and order.
	 * @param urlMap map with URL paths as keys and handler beans (or handler
	 * bean names) as values
	 * @param order the order value for this {@code SimpleUrlHandlerMapping}
	 * @since 5.2
	 * @see #setUrlMap(Map)
	 * @see #setOrder(int)
	 */
	public SimpleUrlHandlerMapping(Map<String, ?> urlMap, int order) {
		setUrlMap(urlMap);
		setOrder(order);
	}


	/**
	 * Map URL paths to handler bean names.
	 * This is the typical way of configuring this HandlerMapping.
	 * <p>Supports direct URL matches and Ant-style pattern matches. For syntax
	 * details, see the {@link org.springframework.util.AntPathMatcher} javadoc.
	 * @param mappings properties with URLs as keys and bean names as values
	 * @see #setUrlMap
	 */
	public void setMappings(Properties mappings) {
		CollectionUtils.mergePropertiesIntoMap(mappings, this.urlMap);
	}

	/**
	 * Set a Map with URL paths as keys and handler beans (or handler bean names)
	 * as values. Convenient for population with bean references.
	 * <p>Supports direct URL matches and Ant-style pattern matches. For syntax
	 * details, see the {@link org.springframework.util.AntPathMatcher} javadoc.
	 * @param urlMap map with URLs as keys and beans as values
	 * @see #setMappings
	 */
	public void setUrlMap(Map<String, ?> urlMap) {
		this.urlMap.putAll(urlMap);
	}

	/**
	 * Allow {@code Map} access to the URL path mappings, with the option to add or
	 * override specific entries.
	 * <p>Useful for specifying entries directly, for example via "urlMap[myKey]".
	 * This is particularly useful for adding or overriding entries in child
	 * bean definitions.
	 */
	public Map<String, ?> getUrlMap() {
		return this.urlMap;
	}


	/**
	 * Calls the {@link #registerHandlers} method in addition to the
	 * superclass's initialization.
	 */
	@Override
	public void initApplicationContext() throws BeansException {
		super.initApplicationContext();
		registerHandlers(this.urlMap);
	}

	/**
	 * Register all handlers specified in the URL map for the corresponding paths.
	 * @param urlMap a Map with URL paths as keys and handler beans or bean names as values
	 * @throws BeansException if a handler couldn't be registered
	 * @throws IllegalStateException if there is a conflicting handler registered
	 */
	protected void registerHandlers(Map<String, Object> urlMap) throws BeansException {
		if (urlMap.isEmpty()) {
			logger.trace("No patterns in " + formatMappingName());
		}
		else {
			urlMap.forEach((url, handler) -> {
				// Prepend with slash if not already present.
				if (!url.startsWith("/")) {
					url = "/" + url;
				}
				// Remove whitespace from handler bean name.
				if (handler instanceof String handlerName) {
					handler = handlerName.trim();
				}
				registerHandler(url, handler);
			});
			logMappings();
		}
	}

	private void logMappings() {
		if (mappingsLogger.isDebugEnabled()) {
			Map<String, Object> map = new LinkedHashMap<>(getHandlerMap());
			if (getRootHandler() != null) {
				map.put("/", getRootHandler());
			}
			if (getDefaultHandler() != null) {
				map.put("/**", getDefaultHandler());
			}
			mappingsLogger.debug(formatMappingName() + " " + map);
		}
		else if (logger.isDebugEnabled()) {
			List<String> patterns = new ArrayList<>();
			if (getRootHandler() != null) {
				patterns.add("/");
			}
			if (getDefaultHandler() != null) {
				patterns.add("/**");
			}
			patterns.addAll(getHandlerMap().keySet());
			logger.debug("Patterns " + patterns + " in " + formatMappingName());
		}
	}

}
